<script setup>
import { computed, defineEmits, defineProps, ref, watch } from 'vue'

const props = defineProps({
  options: Array,
  modelValue: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: 'primary'
  },
  showNoneOption: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

// 用于跟踪"无"选项的状态
const noneChecked = ref(false)

// 计算属性处理选中值
const selectedValue = computed({
  get() {
    return props.modelValue || []
  },
  set(value) {
    emit('update:modelValue', value || [])
  }
})

// 处理"无"选项变化
const handleNoneChange = (checked) => {
  if (checked) {
    // 如果选中"无"，清空其他选项
    selectedValue.value = []
    noneChecked.value = true
  }
}

// 处理其他选项变化
const handleOtherChange = (value) => {
  // 如果有其他选项被选中，取消"无"选项
  if (value && value.length > 0) {
    noneChecked.value = false
  }
  emit('update:modelValue', value)
}

// 监听外部 modelValue 变化，同步 noneChecked 状态
watch(() => props.modelValue, (newVal) => {
  if (!newVal || newVal.length === 0) {
    // 如果没有选中任何选项，"无"选项应该被选中
    noneChecked.value = true
  } else {
    // 如果有选项被选中，"无"选项应该被取消
    noneChecked.value = false
  }
}, { immediate: true })
</script>

<template>
  <div class="el-checkbox-container">
    <el-checkbox-group
        v-model="selectedValue"
        @change="handleOtherChange"
    >
      <el-checkbox-button
          v-for="(item, index) in options"
          :key="index"
          :label="item.key"
      >
        {{ item.name }}
      </el-checkbox-button>
    </el-checkbox-group>

    <el-checkbox-button
        v-if="showNoneOption"
        v-model="noneChecked"
        @change="handleNoneChange"
        label=""
    >
      无
    </el-checkbox-button>
  </div>
</template>

<style scoped lang="scss">
.el-checkbox-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.el-checkbox-button) {
  margin-right: 8px;
  margin-bottom: 8px;
}

:deep(.el-checkbox-button__inner) {
  border-radius: 4px;
}
</style>